package makovo.ajax;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import makovo.data.Items;
import makovo.data.Items.DocumentType;
import makovo.data.Resources;
import makovo.entities.Applicant.ApplicantStep;
import makovo.entities.ApplicantWithDocs;
import makovo.utils.FTPAccess;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.interceptor.SessionAware;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class UploadFile extends HttpServlet implements SessionAware {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();

		String mCurp = (String) session.getAttribute("User.idSender");

		FileItemFactory factory = new DiskFileItemFactory();

		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			// Parse the request
			List items = upload.parseRequest(request);

			if (items.size() > 0) {
				FileItem file = (FileItem) items.get(0);
				String fileType = file.getFieldName();

				FTPAccess.getInstance().makeDir(mCurp);
				FTPAccess.getInstance().removeFile(mCurp + "/" + fileType + ".pdf");

				String remoteFile = FTPAccess.getInstance().uploadFile(file.get(), mCurp + "/" + fileType + ".pdf");

				if (remoteFile != null) {
					DocumentType d = Items.DocumentType.valueByName(file.getFieldName());

					if (d != null)
						Resources.saveFilePath(mCurp, remoteFile, d);
					else
						throw new Exception();

					response.setCharacterEncoding("utf8");
					response.setContentType("application/json");
					PrintWriter out = response.getWriter();

					JSONObject obj = new JSONObject();
					obj.put("remote-file", remoteFile);

					out.print(obj);
				}

			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void setSession(Map<String, Object> session) {

	}
}
